﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Drawing;

namespace ExplorerPlus.Utilities
{
    public static class Web
    {
        /// <summary>
        /// Stores an image from the web to disk.
        /// </summary>
        /// <param name="url">image url</param>
        /// <param name="path">directory path to store image to</param>
        /// <returns>the new path of the saved image path</returns>
        public static string SaveImageToDisk(string url, string path)
        {
            if (System.IO.Directory.Exists(path))
            {
                string savedImagePath = System.IO.Path.Combine(path, System.IO.Path.GetFileName(url));
                if (!File.Exists(savedImagePath))
                {
                    System.Drawing.Image webImage = GetImage(url);
                    webImage.Save(savedImagePath);
                }
                return savedImagePath;
            }

            return string.Empty;
        }
        /// <summary>
        /// returns an image object from a web url stream.
        /// </summary>
        /// <param name="url">image url</param>
        /// <returns>returns an image object from a web url stream.</returns>
        public static System.Drawing.Image GetImage(string url)
        {
            Uri uri = CalculateUri(url);

            if (uri.IsFile)
            {
                using (StreamReader reader = new StreamReader(uri.LocalPath))
                {
                    return Image.FromStream(reader.BaseStream);
                }
            }

            using (WebClient client = new WebClient())
            {
                using (Stream stream = client.OpenRead(uri))
                {
                    return Image.FromStream(stream);
                }
            }
        }
        /// <summary>
        /// Tries to evaluate a url and return its valid location.
        /// </summary>
        public static Uri CalculateUri(string path)
        {
            try
            {
                return new Uri(path);
            }
            catch (UriFormatException)
            {
                path = Path.GetFullPath(path);
                return new Uri(path);
            }
        }

    }
}
